package com.cvmars.jianyou.api.interceptor;

import android.text.TextUtils;
import android.util.Log;


import com.cvmars.jianyou.config.MyConfig;
import com.cvmars.jianyou.utils.DeviceHelper;
import com.orhanobut.hawk.Hawk;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.prefs.Preferences;

import okhttp3.Cookie;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zsm on 2017/6/26
 * <p>
 * 拦截header中的数据
 */

public class HeaderInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

//        Request request = chain.request();
//        Headers.Builder headers = request.headers().newBuilder();
//
        String token = Hawk.get(MyConfig.SP_CACHE_TOKEN);
        String sessionid = Hawk.get(MyConfig.SP_CACHE_SESSION);
//

        Request.Builder builder = chain.request().newBuilder();

        if (token != null) {

            builder.addHeader("Cookie", "csrftoken=" + token + ";sessionid=" + sessionid);
            builder.addHeader("X-CSRFToken", token);
        }

        builder.addHeader("os", "android");
        builder.addHeader("device", DeviceHelper.SerialNumber());
        builder.addHeader("version", DeviceHelper.installVersion());
        if (!TextUtils.isEmpty(MyConfig.Lat)) {
            builder.addHeader("latitude", MyConfig.Lat);
        }
        if (!TextUtils.isEmpty(MyConfig.Lon)) {
            builder.addHeader("longitude", MyConfig.Lon);
        }

//        HashSet<String> preferences = new HashSet<>();
//        preferences.add(token);
//        preferences.add(token.replace("csrftoken","X-CSRFToken"));
//        preferences.add(sessionid);
//        for (String cookie : preferences) {
//            builder.addHeader("Cookie", cookie);
//            Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
//        }


        Response response = chain.proceed(builder.build());


        return response;
    }
}
